<template>
  <div class="change-history">
    <div class="container">
      <div class="table-map">
        <a-row style="margin-bottom: 10px">
          <a-col :span="24">
            <a-button type="primary" @click="kpiAdd()">新增缺陷</a-button>
            <a-button style="margin-left: 15px" v-show="kpi.data.length > 0" @click="gotoDetail()">查看详情</a-button>
            <a-button
              style="margin-left: 15px"
              type="primary"
              @click="clickAllReport()"
              v-show="kpi.data.length > 0"
              :disabled="!kpi.selRowIds.length > 0"
              >一键报工</a-button
            >
          </a-col>
        </a-row>
        <a-table
          class="hte-table-content"
          :row-selection="rowSelection"
          :columns="kpi.columns"
          :data-source="kpi.data"
          bordered
          size="middle"
          :loading="tableLoading"
          :pagination="ipagination"
          @change="handleTableChange"
          :rowKey="(record) => record.id"
        >
          <template slot="bugLevel" slot-scope="text">
            {{ text == '1' ? '致命' : (text == '2' ? '严重' : (text == '3' ? '一般' : '建议/提醒')) }}
          </template>
          <template slot="startDate" slot-scope="text, record">
            {{ dateFormat(record.startDate) }}
          </template>
          <template slot="endDate" slot-scope="text, record">
            {{ dateFormat(record.endDate) }}
          </template>
          <template slot="realCompletionDate" slot-scope="text, record">
            <span v-if="record.detailStatus == '2' || currentUserId != record.handleUserId">{{
              dateFormat(record.realCompletionDate)
            }}</span>
            <a-date-picker
              v-else
              v-model="record.realCompletionDate"
              placeholder="请输入实际完成时间"
              allowClear
              @change="
                (date, dateString) => {
                  realTimeSelect(date, dateString, record)
                }
              "
              :disabled-date="disabledCurrent"
            />
          </template>
          <template slot="reportMemo" slot-scope="text, record">
            <span v-if="record.detailStatus == '2' || currentUserId != record.handleUserId">{{ text }}</span>
            <a-textarea
              v-else
              v-model="record.reportMemo"
              :auto-size="{ minRows: 1 }"
              style="width: 100%"
              placeholder="请填写完成情况，500字内"
              :maxLength="500"
            />
          </template>
          <template slot="delayMemo" slot-scope="text, record">
            <span
              v-if="
                record.detailStatus == '2' || currentUserId != record.handleUserId || delayIds.indexOf(record.id) == -1
              "
              >{{ text }}</span
            >
            <a-textarea
              v-else
              v-model="record.delayMemo"
              :auto-size="{ minRows: 1 }"
              style="width: 100%"
              placeholder="请填写延误原因，500字内"
              :maxLength="500"
            />
          </template>
          <template slot="bugStatus" slot-scope="text, record">
            {{ record.detailStatus != '2' ? '待处理' : initBugStatus(text) }}
          </template>
          <template slot="action" slot-scope="text, record">
            <a v-if="record.detailStatus == '3' && currentUserId == record.handleUserId" @click="detailReport(record)"
              >报工</a
            >
            <a
              v-if="
                record.detailStatus == '2' &&
                currentUserId == record.createUserId &&
                (!record.bugStatus || record.bugStatus == '1')
              "
              @click="closeDetail(record)"
              >关闭</a
            >
            <a
              v-if="
                record.detailStatus == '2' &&
                currentUserId == record.createUserId &&
                (!record.bugStatus || record.bugStatus == '2')
              "
              @click="reOpenDetail(record)"
              style="margin-left: 5px"
              >重新打开</a
            >
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import moment from 'moment'
import Vue from 'vue'
export default {
  name: 'TaskBugList',
  props: {
    hid: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      kpi: {
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 50,
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            title: '缺陷内容',
            align: 'center',
            dataIndex: 'taskContent',
          },
          {
            title: '缺陷等级',
            dataIndex: 'bugLevel',
            align: 'center',
            width: '8%',
            scopedSlots: { customRender: 'bugLevel' },
            sorter: (a, b) => a.bugLevel - b.bugLevel,
          },
          {
            title: '修复开始时间',
            dataIndex: 'startDate',
            align: 'center',
            width: '8%',
            scopedSlots: { customRender: 'startDate' },
          },
          {
            title: '修复完成时间',
            dataIndex: 'endDate',
            align: 'center',
            width: '8%',
            scopedSlots: { customRender: 'endDate' },
          },
          {
            title: '具体执行人员',
            dataIndex: 'handleUserName',
            align: 'center',
            width: '8%',
          },
          {
            title: '实际完成时间',
            dataIndex: 'realCompletionDate',
            align: 'center',
            width: '8%',
            scopedSlots: { customRender: 'realCompletionDate' },
          },
          {
            title: '具体完成情况',
            dataIndex: 'reportMemo',
            align: 'center',
            width: '10%',
            scopedSlots: { customRender: 'reportMemo' },
          },
          {
            title: '延误原因',
            dataIndex: 'delayMemo',
            align: 'center',
            width: '10%',
            scopedSlots: { customRender: 'delayMemo' },
          },
          {
            title: 'bug状态',
            dataIndex: 'bugStatus',
            align: 'center',
            width: '8%',
            scopedSlots: { customRender: 'bugStatus' },
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: '10%',
            scopedSlots: { customRender: 'action' },
          },
        ],
        data: [],
        selRowIds: [],
      },
      tableLoading: false,
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '50'],
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        hideOnSinglePage: false,
        total: 0,
      },
      form: {},
      url: {
        getBugList: '/projectWorkTask/getBugList',
        reportTask: '/projectWorkTask/reportTask',
        batchReportTask: '/projectWorkTask/batchReportTask',
        closeDetail: '/projectWorkTask/closeDetail',
        reOpenDetail: '/projectWorkTask/reOpenDetail',
      },
      addFlag: false,
      currentUserId: '',
      detailId: 0,
      delayFlag: false,
      detailStartDate: '',
      detailEndDate: '',
      reportFlag: false,
      currentIndex: '',
      delayIds: [],
      selectedRowKeys: [],
    }
  },
  mounted() {
    this.initData()
    this.currentUserId = Vue.ls.get(USER_INFO).username
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.kpi.selRowIds = selectedRows
          this.selectedRowKeys = selectedRowKeys
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: !(record.detailStatus == '3' && this.currentUserId == record.handleUserId),
          },
        }),
      }
    },
  },
  methods: {
    kpiAdd() {
      let urlJump = this.$router.resolve({ path: `/dailyBugTaskAdd?id=${this.hid}` })
      window.open(urlJump.href, '_blank')
    },
    gotoDetail() {
      let urlJump = this.$router.resolve({ path: `/dailyBugTaskDetail?id=${this.hid}` })
      window.open(urlJump.href, '_blank')
    },
    dateFormat(date) {
      return date ? moment(date).format('YYYY-MM-DD') : ''
    },
    clickAllReport() {
      if (this.kpi.selRowIds.length == 0) {
        this.$message.warning('请选择要报工的明细记录')
        return
      }
      for (var i = 0; i < this.kpi.selRowIds.length; i++) {
        if (this.delayIds.indexOf(this.kpi.selRowIds[i].id) > -1 && !this.kpi.selRowIds[i].delayMemo) {
          this.$message.warning(`缺陷内容为${this.kpi.selRowIds[i].taskContent}的记录已延误，请填写延误原因`)
          return
        }
        if (!this.kpi.selRowIds[i].realCompletionDate) {
          this.$message.warning(`缺陷内容为${this.kpi.selRowIds[i].taskContent}的记录实际完成时间未填写，请填写`)
          return
        }
      }

      let arr = []
      for (var i = 0; i < this.kpi.selRowIds.length; i++) {
        var obj = {}
        obj.id = this.hid
        obj.detailId = this.kpi.selRowIds[i].id
        obj.reportMemo = this.kpi.selRowIds[i].reportMemo ? this.kpi.selRowIds[i].reportMemo : '已完成'
        obj.delayMemo = this.kpi.selRowIds[i].delayMemo
        obj.comfirmFlag = true
        obj.realCompletionDate = this.kpi.selRowIds[i].realCompletionDate
        obj.bugType = '1'
        arr.push(obj)
      }
      const that = this
      this.$confirm({
        title: '是否确认一键报工',
        onOk() {
          postAction(that.url.batchReportTask, arr)
            .then((res) => {
              if (res.code === 200) {
                that.$message.success('一键报工成功')
                that.initData(that.hid)
              } else {
                const msg = res.message == null ? res.result : res.message
                that.$message.error(msg)
              }
              that.kpi.selRowIds = []
              that.selectedRowKeys = []
            })
            .catch((err) => {
              console.log(err)
            })
        },
        onCancel() {},
      })
    },
    detailReport(record) {
      if (!record.realCompletionDate) {
        this.$message.warning('实际完成时间不能为空')
        return
      }
      if (this.delayFlag && !record.delayMemo) {
        this.$message.warning('延误原因不能为空')
        return
      }
      if (!record.reportMemo) {
        record.reportMemo = '已完成'
      }
      var obj = {}
      obj.id = this.hid
      obj.detailId = record.id
      obj.reportMemo = record.reportMemo
      obj.delayMemo = record.delayMemo
      obj.comfirmFlag = true
      obj.realCompletionDate = record.realCompletionDate
      obj.bugType = '1'
      const that = this
      this.$confirm({
        title: '是否确认报工',
        onOk() {
          postAction(that.url.reportTask, obj)
            .then((res) => {
              if (res.code === 200) {
                that.$message.success('报工成功')
                that.initData(that.hid)
              } else {
                const msg = res.message == null ? res.result : res.message
                that.$message.error(msg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        },
        onCancel() {},
      })
    },
    initBugStatus(text) {
      switch (text) {
        case 1:
          return '复测不通过'
          break
        case 2:
          return '复测通过'
          break
        default:
          return '待复测'
      }
    },
    closeDetail(record) {
      const that = this
      this.$confirm({
        title: '是否确认关闭该缺陷',
        onOk() {
          postAction(that.url.closeDetail, record)
            .then((res) => {
              if (res.code === 200) {
                that.$message.success('关闭缺陷成功')
                that.initData(that.hid)
              } else {
                const msg = res.message == null ? res.result : res.message
                that.$message.error(msg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        },
        onCancel() {},
      })
    },
    reOpenDetail(record) {
      const that = this
      this.$confirm({
        title: '是否确认重新打开缺陷',
        onOk() {
          postAction(that.url.reOpenDetail, record)
            .then((res) => {
              if (res.code === 200) {
                that.$message.success('重新打开缺陷成功')
                that.initData(that.hid)
              } else {
                const msg = res.message == null ? res.result : res.message
                that.$message.error(msg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        },
        onCancel() {},
      })
    },
    disabledCurrent(current) {
      return current > moment().endOf('day')
    },
    realTimeSelect(date, dateString, record) {
      if (dateString && moment(dateString).diff(moment(record.endDate), 'day') > 0 ) {
        this.delayFlag = true
      } else {
        this.delayFlag = false
        record.delayMemo = ''
      }
    },
    handleTableChange(pagination, filters, sorter) {
      if (this.tableLoading) {
        return
      }
      this.ipagination = pagination
      this.ipagination.pageNo = this.ipagination.current
      this.initData()
    },
    initData() {
      if (this.tableLoading) {
        return
      }
      this.tableLoading = true
      const _this = this
      getAction(this.url.getBugList, {
        bugId: this.hid,
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
      })
        .then((res) => {
          if (res.code === 200 && res.result && res.result.records) {
            this.kpi.data = res.result.records || []
            if (_this.kpi.data.length == 0) {
              this.kpiAdd()
              this.$emit('closeBugModal')
            }
            this.ipagination.total = res.result.total
            _this.kpi.data.forEach((item) => {
              if (
                item.handleUserId === _this.currentUserId &&
                item.detailStatus != '2' &&
                (item.planCompletionDate
                  ? moment(item.planCompletionDate).diff(item.endDate, 'day') > 0 ||
                    (item.realCompletionDate
                      ? moment(item.realCompletionDate).diff(item.endDate, 'day') > 0
                      : moment(moment().format('YYYY-MM-DD')).diff(item.endDate, 'day') > 0)
                  : item.realCompletionDate
                  ? moment(item.realCompletionDate).diff(item.endDate, 'day') > 0
                  : moment(moment().format('YYYY-MM-DD')).diff(item.endDate, 'day') > 0)
              ) {
                _this.delayIds.push(item.id)
              }
            })
          } else {
            this.$message.error(res.message)
            this.ipagination.total = 0
          }
          this.tableLoading = false
        })
        .catch((res) => {
          this.tableLoading = false
        })
    }
  },
}
</script>
<style lang="less" scoped>
.change-history {
  .content {
    width: 80%;
    color: #333;
  }
  .time {
    color: #999;
  }
  .pagecontent {
    padding: 10px 2px 0 2px;
    text-align: right;
  }
  .loaddingbox {
    text-align: center;
    padding: 50px;
  }
}
</style>
